#!/bin/sh

input_file=$1
fileline=`cat ${input_file} | grep -v  "#"`
echo "fileline---->"${fileline}

# Check
file_num=`cat ${input_file} | grep -v "#" | grep -v '^$' | wc -l`
echo "file_num="${file_num}
if [ ${file_num} != 1 ]
then 
        echo_error  "error: ${input_file}, file num is not one."
        exit;
fi

# Example
#VerifyServices----http://120.194.3.112:1000/ddc_update/VerifyServices.tgz----/home/IOTPlatform/----init.conf----/home/IOTPlatform/stopVerifyServices.sh----/home/IOTPlatform/startVerifyServices.sh

# Split
app_name=`echo ${fileline} | awk -F"----" '{print $1}'`
app_tgz_url=`echo ${fileline} | awk -F"----" '{print $2}'`
app_deploy_dir=`echo ${fileline} | awk -F"----" '{print $3}'`
app_proc_config=`echo ${fileline} | awk -F"----" '{print $4}'`
app_proc_stop=`echo ${fileline} | awk -F"----" '{print $5}'`
app_proc_start=`echo ${fileline} | awk -F"----" '{print $6}'`

if [ "/" == ${app_deploy_dir: -1} ]
then
        app_deploy_dir=${app_deploy_dir%?}
fi

echo -e  "---->${git_proc_name}--${git_code_url}--${git_deploy_dir}--${git_proc_config}--${git_proc_stop}--${git_proc_start}"

# Prepare
backupDir=backup_config
time_str=`date  +%Y%m%d%H%M%S`

# Start
echo -e  "start ................................................................."


#1.download Code
echo -e  "download Code"
header_auth="Authorization:Basic dmNvbV9vbmxpbmV1cGRhdGU6VmNvbUAyMDE5"
app_tgz_name=${app_name}_${time_str}.tgz
rm -fr ${app_tgz_name}  ${app_name}
wget --header "${header_auth}"  ${app_tgz_url}  -O  ${app_tgz_name}  -q
tar zxf ${app_tgz_name}



#2.backup Config
echo -e  "backup Config"
original_config_dir="${app_deploy_dir}/${app_name}"
mkdir   ${original_config_dir}  -p

back_config_dir="${backupDir}/${app_name}_${time_str}"
mkdir   ${back_config_dir}  -p

_app_proc_config=`echo ${app_proc_config}|awk -F "," '{print $1}'`
original_config_file="${original_config_dir}/${_app_proc_config}"
back_config_backfile="${back_config_dir}/${_app_proc_config}"

echo "cp -fr  ${original_config_file}    ${back_config_backfile}"
cp -fr  ${original_config_file}    ${back_config_dir}


#3.stop Proc
echo -e  "stop Proc"
${app_proc_stop}


#4.backup Old App
echo -e  "backup Old App"
mv  ${app_deploy_dir}/${app_name}       ${app_deploy_dir}/${app_name}_${time_str}

#5.prepare New App
echo -e  "prepare New App"
cp  -fr ${app_name}  ${app_deploy_dir} 
echo "cp -fr  ${back_config_backfile}    ${original_config_dir}"
cp -fr  ${back_config_backfile}    ${original_config_dir}


#6.start Proc
echo -e  "start Proc"
${app_proc_start}

echo  -e  "Proc  Update is success !!!... "


